<?php

namespace yak\layui\widgets\form;

use yii\helpers\Html;
use yii\helpers\Url;
use yii\web\View;
use yii\widgets\InputWidget;

/**
 * Class IconPicker
 * @package yak\layui\widgets\form
 */
class UploadWell extends InputWidget
{
    /**
     * @var string
     */
    public $type = 'drag'; // 0 渲染 1 click

    /**
     * @var
     */
    public $url = ['upload'];

    /**
     * @var string
     */
    public $host = '';

    /**
     * @var string
     */
    public $imgUrl = '';

    public function run()
    {
        $id = $this->getId();
        $url = Url::toRoute($this->url);
        $this->imgUrl = empty($this->imgUrl) ? $this->model[$this->attribute] : $this->imgUrl;
        $label = $this->model->getAttributeLabel($this->attribute);
        $this->script($id, $url);
        echo Html::hiddenInput($this->attribute, $this->imgUrl, ['id' => $id . '-upload-input']);
        return call_user_func_array([$this, 'render' . ucfirst($this->type)], [$id, $url, $label]);
    }

    private function script($id, $url)
    {
        $js = <<<JS
        //拖拽上传
          layui.use(['upload'], function () {
              var upload = layui.upload
              upload.render({
                elem: '#{$id}'
                , url: '{$url}'
                , done: function(res){
                    if (res.status === 200) {
                        layer.msg('上传成功');
                        layui.$('#{$id}-upload-view').removeClass('layui-hide').find('img').attr('src', '{$this->host}' + res.src);
                        layui.$('#{$id}-upload-input').val(res.src)
                    } else {
                        layer.alert(res.msg)
                    }
                }
              });
          })
JS;
        $this->getView()->registerJs($js, View::POS_END);
    }

    public function renderDrag($id, $url, $label)
    {
        $html = '<i class="layui-icon"></i>
            <p>点击上传，或将文件拖拽到此处</p>
            <div class="' . ($this->imgUrl?'':'layui-hide') . '" id="' . $id . '-upload-view">
                <hr>
                <img src="' . $this->host . $this->imgUrl . '" alt="上传成功后渲染" style="max-width: 196px">
            </div>';

        return Html::tag('div', $html, [
            'class' => 'layui-upload-drag', 'id' => $id
        ]);
    }

    public function renderNormal($id, $url, $label)
    {
        $html = '<label class="layui-form-label">' . $label . '</label>
                    <div class="layui-input-block">
                        <button type="button" class="layui-btn" id="test1">上传图片</button>
                        <div class="' . ($this->imgUrl?'':'layui-hide') . ' help-block" id="' . $id . '-upload-view">
                            <img src="' . $this->host . $this->imgUrl . '" style="max-width: 196px">
                        </div>
                    </div>';

        return Html::tag('div', $html, [
            'class' => 'layui-form-item', 'id' => $id
        ]);
    }
}